//给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。 
//
// 
//
// 示例 1： 
//
// 
//输入：n = 3
//输出：[[1,2,3],[8,9,4],[7,6,5]]
// 
//
// 示例 2： 
//
// 
//输入：n = 1
//输出：[[1]]
// 
//
// 
//
// 提示： 
//
// 
// 1 <= n <= 20 
// 
// Related Topics 数组 矩阵 模拟 
// 👍 541 👎 0

package leetcode.editor.cn;
/**
 * [59]螺旋矩阵 II
 */
public class SpiralMatrixIi {
    public static void main(String[] args) {
        Solution solution = new SpiralMatrixIi().new Solution();
        solution.generateMatrix(3);
    }
    //leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    // 个人
    public int[][] generateMatrix2(int n) {
        int [][] result = new int[n][n];
        int start = 1, end = n*n;
        int y = 0;
        int x = 0;
        while (start <= end) {
            for (x = y; x <= n-y-1; x++) {
                result[y][x] = start;
                start++;
            }
            if (start > end) {
                break;
            }

            x = x-1;
            for (y = y+1; y <= x-1; y++) {
                result[y][x] = start;
                start++;
            }
            if (start > end) {
                break;
            }

            y = x;
            for (; x >= n-y-1; x--) {
                result[y][x] = start;
                start++;
            }
            if (start > end) {
                break;
            }

            x = x + 1;
            for (y = y-1; y >= x+1; y--) {
                result[y][x] = start;
                start++;
            }
            y++;
        }
        return result;
    }

    // 优化
    public int[][] generateMatrix(int n) {
        int [][] result = new int[n][n];
        int start = 1, end = n*n;
        int c = 0;
        int x = 0;
        while (start <= end) {
            for (x = c; x < n-c; x++) {
                result[c][x] = start;
                start++;
            }

            for (x = c+1; x < n-c; x++) {
                result[x][n-c-1] = start;
                start++;
            }

            for (x=n-c-2; x >= c; x--) {
                result[n-c-1][x] = start;
                start++;
            }

            for (x = n-c-2; x > c; x--) {
                result[x][c] = start;
                start++;
            }
            c++;
        }
        return result;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}